package drds.binlog.server.netty.handler;

import drds.binlog.protocol.protocol_proto.Handshake;
import drds.binlog.protocol.protocol_proto.Packet;
import drds.binlog.protocol.protocol_proto.PacketType;
import drds.binlog.server.netty.Nettys;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * handshake交互
 */
public class HandshakeInitializationHandler extends SimpleChannelHandler
{

    private static final Logger logger = LoggerFactory.getLogger(HandshakeInitializationHandler.class);
    // support to maintain socket channel.
    private ChannelGroup channelGroup;//channelGroup

    public HandshakeInitializationHandler(ChannelGroup channelGroup)
    {
        this.channelGroup = channelGroup;
    }

    public void channelOpen(ChannelHandlerContext channelHandlerContext, ChannelStateEvent channelStateEvent) throws Exception
    {
        // add new socket channel in channel container, used to manage sockets.
        if (channelGroup != null)
        {
            channelGroup.add(channelHandlerContext.getChannel());
        }

        byte[] body = Packet.newBuilder()
                .setType(PacketType.handshake)
                .setBody(Handshake.newBuilder().build().toByteString())
                .build()
                .toByteArray();
        Nettys.write(channelHandlerContext.getChannel(), body, null);
        logger.info("send handshake initialization packet to : {}", channelHandlerContext.getChannel());
    }
}
